<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="手机/昵称">
        <el-input v-model="queryParams.keyWord" clearable placeholder="请输入搜索关键词" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="list" v-loading="loading">
      <el-table-column prop="nickName" label="昵称" />
      <el-table-column label="头像">
        <template #default="{ row }">
          <el-image
            v-if="row.userIcon != null && row.userIcon != ''"
            style="width: 40px; height: 40px"
            :src="row.userIcon"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="createTime" label="注册时间" />
      <el-table-column label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="stateTagType[row.state as keyof typeof stateTagType] ?? 'info'">
            {{ stateMap[row.state as keyof typeof stateMap] ?? '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getPage } from '@/api/user/user'
import Pagination from '@/components/Pagination/index.vue'

interface UserItem {
  id: number
  nickName: string
  userIcon: string
  realName: string
  mobile: string
  createTime: string
  state: '0' | '1' | '2'
  [key: string]: any
}

interface QueryParams {
  pageNum: number
  pageSize: number
  keyWord: string
}

// 查询参数
const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyWord: '',
})

const list = ref<UserItem[]>([])
const total = ref(0)
const loading = ref(false)

const stateMap = {
  '0': '正常',
  '1': '停用',
  '2': '锁定',
} as const

const stateTagType = {
  '0': 'success',
  '1': 'danger',
  '2': 'warning',
} as const

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getPage(queryParams)
    list.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 重置查询条件
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.keyWord = ''
  getList()
}

onMounted(() => {
  getList()
})
</script>
